﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace System.Windows.Automation.Peers
{
    /// <summary>
    /// Implements extensions for <see cref="WindowAutomationPeer"/> class.
    /// </summary>
    public static class WindowAutomationPeerExtensions
    {
        /// <summary>
        /// Finds the respective child control with name 'name' and casts it to the given type.
        /// </summary>
        /// <typeparam name="TType"></typeparam>
        /// <param name="peer"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentOutOfRangeException">In case no child control with provided name was found.</exception>
        /// <exception cref="ArgumentException">In case the found child control cannot be casted to TType.</exception>
        public static TType GetProvider<TType>(this WindowAutomationPeer peer, string name)
            where TType : AutomationPeer
        {
            var children = peer.GetChildren();
            var untypedChild = children.FirstOrDefault(w => string.CompareOrdinal(w.GetAutomationId(), name) == 0);
            if (null == untypedChild)
            {
                var names = from c in children
                            select c.GetAutomationId();
                var msg = string.Format("'name' does not specify a valid child element!\r\nValid names are:\r\n{0}",
                    string.Join(",", names));
                throw new ArgumentOutOfRangeException(msg);
            }

            var child = (TType)untypedChild;
            if (null == child)
                throw new ArgumentException("Child 'name' is not of type '" + typeof(TType).Name + "'!");

            return child;
        }

    }
}
